import { Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { DanmakuOptions } from 'danmaku'
import { RedisService } from '../redis/RedisService'

@Injectable()
export class DanmakuFilter implements DanmakuOptions {
  private redis: RedisService
  private readonly maxLength: number
  private readonly filterSpecialChars: boolean
  private readonly fullWidthToHalf: boolean
  private readonly deduplicate: boolean

  constructor(private readonly configService: ConfigService) {
    this.redis = new RedisService(this.configService)
    this.maxLength = this.configService.get('DANMAKU_MAX_LENGTH', 100)
    this.filterSpecialChars = this.configService.get('DANMAKU_FILTER_SPECIAL_CHARS', true)
    this.fullWidthToHalf = this.configService.get('DANMAKU_FULL_WIDTH_TO_HALF', true)
    this.deduplicate = this.configService.get('DANMAKU_DEDUPLICATE', true)
  }

  async process(text: string): Promise<string | null> {
    if (!text || !text.trim()) {
      return null
    }

    // 基础检查
    if (text.length > 100) {
      return null
    }

    // 预处理文本
    text = this.preprocess(text)

    return text
  }

  private preprocess(text: string): string {
    // 去除特殊字符
    text = text.replace(/[\u200b-\u200f\u2028-\u202f\u2060-\u206f]/g, '')

    // 全角转半角
    text = text.replace(/[\uff01-\uff5e]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) - 0xfee0))

    // 去除重复字符
    text = text.replace(/(.)\1{5,}/g, '$1$1$1$1$1')

    return text.trim()
  }
}
